package com.hxl.tech.gateway.auth.service;

import com.hxl.tech.gateway.auth.exception.AuthException;
import com.hxl.tech.gateway.auth.model.User;
import com.hxl.tech.gateway.auth.util.AliDayuUtil;
import com.hxl.tech.gateway.common.constant.AppConstant;
import com.hxl.tech.gateway.common.constant.Result;
import com.hxl.tech.gateway.common.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class SmsService {

    private final UserService userService;

    @Value("${spring.profiles.active:default}")
    private String profile;

    @Autowired
    private AliDayuUtil aliDayuUtil;

    public void sendCode(String phone) {

        String key = AppConstant.REDIS_SMS_CODE + phone;

        if (RedisUtil.isExists(key)) {
            throw new AuthException("请不要重复发送验证吗");
        }
        String code = generateCode(4);
        aliDayuUtil.sendMsg(phone, code);

        RedisUtil.set(AppConstant.REDIS_SMS_CODE + phone, code, 3, TimeUnit.MINUTES);
        RedisUtil.set(AppConstant.REDIS_SMS_CODE_COUNT + phone, 0, 3, TimeUnit.MINUTES);
    }

    public void verify(String phone, String code) {

        Integer count = (Integer) RedisUtil.get(AppConstant.REDIS_SMS_CODE_COUNT + phone);
        if (Objects.isNull(count) || count >= 3) {
            throw new AuthException(Result.E10020);
        }

        String redisCode = (String) RedisUtil.get(AppConstant.REDIS_SMS_CODE + phone);
        if (!code.equals(redisCode)) {
            RedisUtil.set(AppConstant.REDIS_SMS_CODE_COUNT + phone, count+1, 3, TimeUnit.MINUTES);
            throw new AuthException(Result.E10019);
        }
    }

    public String generateCode(Integer codeLength) {
        long nextInt = ThreadLocalRandom.current().nextLong(Long.parseLong(StringUtils.rightPad("9", codeLength, "0")))
                + Long.parseLong(StringUtils.rightPad("1", codeLength, "0"));
        if (nextInt < 0) {
            nextInt = -nextInt;
        }
        String str = nextInt + "";
        return str;
    }

}